package com.automobile.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.automobile.domain.*;
import com.automobile.service.CollectService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.embedded.ConnectionProperties;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import com.automobile.service.AnnounceService;
import com.automobile.service.CategoryService;
import com.automobile.service.ImgService;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping("/announce")
public class AnnounceController {
	
	@Autowired
	private AnnounceService announceService;
	
	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private ImgService imgService;

	@Autowired
    private CollectService collectService;
	
	@RequestMapping("/seek")
	public @ResponseBody BeanPage findAnnounce(@RequestBody BeanPage beanPage) {
		BeanPage resultBeanPage = announceService.findPaste(beanPage);
		return resultBeanPage;
	}

	@RequestMapping("/message")
    public @ResponseBody Announce message(@RequestBody int id){
        Announce announce = announceService.findAnnounceById(id);
        return announce;
    }

	
	@RequestMapping("/upload")
	public @ResponseBody String upload(HttpServletRequest request,
			@RequestParam("files") MultipartFile[] files,
			@RequestParam("jsonStr") String jsonStr) throws JsonParseException, JsonMappingException, IOException {
		

		ObjectMapper mapper = new ObjectMapper();
		Announce announce = mapper.readValue(jsonStr, Announce.class);
//		int carBrandId = categoryService.findCarBrandIdByName(announce.getCarBrand());
//		int carTypeId = categoryService.findCarTypeIdByName(announce.getCarType());
//
//		announce.setCarBrandId(carBrandId);
//		announce.setCarTypeId(carTypeId);
		
		announceService.save(announce);
		
		//存放地址
//		String path = request.getSession().getServletContext().getRealPath("/static/files/");
        String path= ResourceUtils.getURL("classpath:").getPath()+"static/files/";

        path = URLDecoder.decode(path, "utf-8");


        System.out.println("path === "+path);

		//存放目录不存在时，创建目录
		File file = new File(path);
		if(!file.exists()) {
			file.mkdirs();
		}
		if(files!=null&&files.length>0) {
			for(int i = 0;i<files.length;i++) {
				//获取文件名
				String fileName = files[i].getOriginalFilename();
				fileName = fileName.substring(fileName.lastIndexOf("."));
				//创建唯一值
				String uuid = UUID.randomUUID().toString().replace("-", "");
				//唯一值+文件名
				fileName = uuid+"_"+fileName;
				imgService.save(new Img("files/"+fileName, announce.getId()));
				
				try {
					//将文件写道指定目录
					files[i].transferTo(new File(path, fileName));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		return "success";
	}

	@RequestMapping("/findCollect")
    public @ResponseBody int findCollect(@RequestBody int id){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(user == null){
            return -1;
        }
        return collectService.findCollect(user.getId(), id);
    }

	@RequestMapping("/taggleCollect")
    public @ResponseBody int deleteCollect(@RequestBody int id){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(user == null){
            return -1;
        }
        return collectService.taggleAnnounce(user.getId(),id);
    }
	
	/*
	@RequestMapping("/upload")
	public @ResponseBody String upload(HttpServletRequest request,
			@RequestParam(value="files",required=false)MultipartFile[] uploadFile,
			@RequestParam(value="") String name) {
		return "success";
	}
	 */
	
	/*
	@RequestMapping("/upload")
	public @ResponseBody String upload(HttpServletRequest request,
	@RequestParam(value="file",required=false)MultipartFile[] uploadFile) {
		return "success";
	}
	*/



    //----------------------------------backstage----------------------------------//

    @RequestMapping("/findByUserId")
    public @ResponseBody List<Announce> findAnnounce() {
        List<Announce> announces = announceService.findUserPaste(2);
        System.out.println(announces);
        return announces;
    }
	
}
